import React, { useState, useEffect } from 'react';
import './index.less';

type CarouselPropsType = {
  direction?: string;
};

const images = [
  './images/1.jpg',
  './images/2.jpg',
  './images/3.jpg',
  './images/4.jpg',
  './images/5.jpg',
];

const Carousel: React.FC<CarouselPropsType> = ({ direction = 'left' }) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    console.log('currentIndex', currentIndex);
    const id = setInterval(() => {
      setCurrentIndex((prevIndex) => {
        // 这里用的了传入回调函数的方式，可以获取上一次index的值
        console.log(prevIndex);
        let newIndex = prevIndex + 1;
        if (newIndex >= images.length) {
          newIndex = 0;
        }
        console.log(prevIndex, newIndex);
        return newIndex;
      });
    }, 3000);

    return () => {
      // 注意要把定时器清除
      clearInterval(id);
    };
    // 你的 Effect 确实没有使用任何响应式值，则它仅在 初始渲染后 运行
  }, []);

  // 也可以这么写但是这种方法没办法实现点击哪一张图片显示
  // useEffect(() => {
  //   console.log('currentIndex', currentIndex);
  //   setTimeout(() => {
  //     if (currentIndex === images.length - 1) {
  //       setCurrentIndex(0);
  //     } else {
  //       setCurrentIndex(currentIndex + 1);
  //     }
  //   }, 3000);
  // }, [currentIndex]);

  const handleArrowClick = (index: number) => {
    setCurrentIndex(index);
  };

  const handleDotClick = (index: number) => {
    setCurrentIndex(index);
  };

  return (
    <div className="carousel">
      <div className="carousel-images">
        <img src={images[currentIndex]} alt="" />
      </div>
      <div className="carousel-arrows">
        <button onClick={() => handleArrowClick(currentIndex - 1)}>
          pre
          <i className="fa fa-angle-left" />
        </button>
        <button onClick={() => handleArrowClick(currentIndex + 1)}>
          next <i className="fa fa-angle-right" />
        </button>
      </div>
      <div className="carousel-dots">
        {images.map((_, index) => (
          <button key={index} onClick={() => handleDotClick(index)}>
            {currentIndex === index && <i className="fa fa-circle" />}
          </button>
        ))}
      </div>
    </div>
  );
};

export default Carousel;
